package com.logansoft.zhxypkoa.utils;

import java.util.Collection;

import org.springframework.data.mapping.context.PersistentEntities;
import org.springframework.data.rest.core.RepositoryConstraintViolationException;
import org.springframework.data.rest.core.ValidationErrors;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.Errors;

public class RestVerifyUtils {

    public static void reject(Object target, String errorCode, String message) {
        PersistentEntities entities = SpringUtils.getBean("persistentEntities", PersistentEntities.class);
        Errors errors = new ValidationErrors(target, entities);
        errors.reject(errorCode, message);
        throw new RepositoryConstraintViolationException(errors);
    }

    public static void rejectValue(Object target, String field, String errorCode, String message) {
        PersistentEntities entities = SpringUtils.getBean("persistentEntities", PersistentEntities.class);
        Errors errors = new ValidationErrors(target, entities);
        errors.rejectValue(field, errorCode, message);
        throw new RepositoryConstraintViolationException(errors);
    }

    public static void rejectValueIfNull(Object target, String field, String errorCode, String message) {
        if (target == null) {
            PersistentEntities entities = SpringUtils.getBean("persistentEntities", PersistentEntities.class);
            Errors errors = new ValidationErrors(target, entities);
            errors.rejectValue(field, errorCode, message);
            throw new RepositoryConstraintViolationException(errors);
        }
    }

    public static <T> void rejectIfEmpty(Collection<T> target, String errorCode, String message) {
        if (CollectionUtils.isEmpty(target)) {
            PersistentEntities entities = SpringUtils.getBean("persistentEntities", PersistentEntities.class);
            Errors errors = new ValidationErrors(target, entities);
            errors.reject(errorCode, message);
            throw new RepositoryConstraintViolationException(errors);
        }
    }
}
